package cn.fl.mfr.web.controller;

import java.lang.reflect.Field;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.fl.mfr.web.transform.MfrRlPsnVOTransform;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysDictionaryService;
import com.alibaba.fastjson.JSON;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.base.mfr.dto.BaseMfrRlPsnDTO;
import fl.spl.facade.framework.constant.SplSystemConstant;
import net.sf.json.JSONArray;
import cn.cmm.base.framework.utils.CollectionUtils;
import fl.spl.facade.framework.enums.CommonOpTypCdEnum;
import fl.spl.facade.mfr.api.IMfrInfoModDtlApiService;
import fl.spl.facade.mfr.condition.MfrInfoModDtlQC;
import fl.spl.facade.mfr.constant.MfrInfoConstant;
import fl.spl.facade.mfr.dto.MfrInfoModDtlDTO;
import fl.spl.facade.mfr.dto.MfrRlPsnDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mfr.web.service.IMfrRlPsnService;
import cn.fl.mfr.web.vo.MfrRlPsnVO;
import fl.spl.facade.mfr.condition.MfrRlPsnQC;
import fl.spl.facade.spl.constant.SplInfoConstant;

/**
 * @Description: 厂商关联人员信息表 控制层
 */
@Controller
@RequestMapping("/mfr/mfrrlpsn")
public class MfrRlPsnController extends BaseController {

	/**
	 * MfrRlPsn 服务层BEAN
	 */
	@Autowired
	private IMfrRlPsnService mfrRlPsnService;

	@Autowired
	private IMfrInfoModDtlApiService mfrInfoModDtlApiService;
	
	@Autowired
	private ISysDictionaryService sysDictionaryService  ;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {

		ModelAndView view = new ModelAndView("mfr/mfrRlPsn/mfrRlPsnList");
		
		return view;
	}
	
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {

		ModelAndView view = new ModelAndView("mfr/mfrRlPsn/mfrRlPsnAdd");
		
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mfr/mfrRlPsn/mfrRlPsnModify");
		view.addObject("id", id);
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
		String isMask = request.getParameter("isMask");
		ModelAndView view = new ModelAndView("mfr/mfrRlPsn/mfrRlPsnDetail");
		view.addObject("id", id);
		if(StringUtils.isNotEmpty(isMask)){
			view.addObject("isMask", isMask);
		}else{
			view.addObject("isMask", "0");
		}
		BaseLogUtils.newWebLogger("加载例子详细页面").setLogOperType(LogOperEnum.REQ)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
				.setWarning(false)
				.info();
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String mfrId = request.getParameter("mfrId");
		String isMaskStr = request.getParameter("isMask");
		ListPageVO<MfrRlPsnVO> listPage=null;
		int isMask = 0 ;
		//根据角色查询是否需要掩码
		String roleisEncrypt = this.sysDictionaryService.getRoleisEncrypt();
		BaseLogUtils.newWebLogger("根据角色查询是否需要掩码").setLogOperType(LogOperEnum.RESP)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
				.setWarning(false)
				.setKeys("roleisEncrypt", JSON.toJSONString(roleisEncrypt))
				.info();
		if(StringUtils.isNotEmpty(isMaskStr) && BaseConstant.IS_YESNO_YES_STR.equals(isMaskStr)
				&& BaseConstant.IS_YESNO_YES_STR.equals(roleisEncrypt)){
			isMask = 1 ;
		}
		if(StringUtils.isEmpty(mfrId)){
			listPage = new ListPageVO<MfrRlPsnVO>(this.setMfrRlPsnList(null), 0);
			return listPage;
		}else {
			Pager page = new Pager();
			if (StringUtils.isNotEmpty(currentPage)) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

			if (StringUtils.isNotEmpty(currentPage)) {
				page.setEveryPage(Integer.parseInt(pageSize));
			}

			MfrRlPsnQC qc = new MfrRlPsnQC();
			qc.setMfrId(Long.valueOf(mfrId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsValid(BaseConstant.IS_YESNO_YES);

			page.setCondition(qc);
			Pager pager = this.mfrRlPsnService.searchListPageByMask(page,isMask);
			List<MfrRlPsnVO> list = (List<MfrRlPsnVO>) pager.getResultList();
			//将未存在的必输联系人添加
			list=this.setMfrRlPsnList(list);
			listPage = new ListPageVO<MfrRlPsnVO>(list, pager.getTotalCount());
			BaseLogUtils.newWebLogger("初始化供应商联系人列表页面数据").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.setKeys("listPage", JSON.toJSONString(listPage))
					.info();
		}
		return listPage;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		MfrRlPsnVO entity = null;
		try {
			entity = new MfrRlPsnVO();
			//TODO ADD PARAM
			Long id = this.mfrRlPsnService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据不存在!");
			return result;
		}
		MfrRlPsnVO entity = null;
		try {
			entity = new MfrRlPsnVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.mfrRlPsnService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		
		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		try {
			this.mfrRlPsnService.removeById(Long.valueOf(id));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		
		try {
			MfrRlPsnVO vo = this.mfrRlPsnService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
			}
			result.setData(vo);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		
		return result;
	}
	
	/**
	 * 封装必输联系人信息
	 * @param voList
	 */
	private List<MfrRlPsnVO> setMfrRlPsnList(List<MfrRlPsnVO> voList){
		//证件类型
		List<KeyValueVO> certTypCdList = this.mfrRlPsnService.searchCertTypCdList();
		//获取默认证件类型名称
		String defCodNm = "";
		for (KeyValueVO keyValueVO : certTypCdList) {
			if(keyValueVO.getKey().equals(SplInfoConstant.CODE_CERT_TYP_DEF_CD)){
				defCodNm = keyValueVO.getValue();
			}
		}
		//联系人类型
		List<KeyValueVO> rlTypCDList = this.mfrRlPsnService.searchRlTypCdList();
		Map<String,MfrRlPsnVO> map=new HashMap<String,MfrRlPsnVO>();
		//查询出所有必输联系人信息
		if(null != rlTypCDList && rlTypCDList.size()>0) {
			for (KeyValueVO keyValueVO : rlTypCDList) {
				if(!(keyValueVO.getKey().equals(SplInfoConstant.SPL_RL_TYP_CD_ACTUAL_2) || keyValueVO.getKey().equals("10") ||keyValueVO.getKey().equals("11") || keyValueVO.getKey().equals("12") || keyValueVO.getKey().equals("13") ) ) {
					MfrRlPsnVO vo = new MfrRlPsnVO();
					vo.setRlTypCd(keyValueVO.getKey());
					vo.setRlTypCdNm(keyValueVO.getValue());
					vo.setCertTypCd(SplInfoConstant.CODE_CERT_TYP_DEF_CD);
					vo.setCertTypCdNm(defCodNm);
					vo.setIsDel(BaseConstant.IS_YESNO_NO);
					vo.setIsDefault(BaseConstant.IS_YESNO_YES);
					map.put(keyValueVO.getKey(), vo);
				}
			}
		}
		//判断修改的联系人信息中是否存在必输的联系人
		if(null != voList && voList.size()>0){
			//循环将已经存在的vo信息
			for (MfrRlPsnVO mfrRlPsnVO : voList) {
				//如果存在必输联系人，将必输Map中联系人去除
				if(map.containsKey(mfrRlPsnVO.getRlTypCd())){
					map.remove(mfrRlPsnVO.getRlTypCd());
				}
			}
		}else{//新增时或修改时无联系人信息，创建联系人
			voList=new ArrayList<MfrRlPsnVO>();
		}
		//将去除重复后的必输联系人添加到联系人列表中
		if(null != map && map.size()>0){
			for (Map.Entry<String, MfrRlPsnVO> entry : map.entrySet()) {
				voList.add(entry.getValue());
			}
		}
		return voList;
	}

	/**
	 * 变更审核页面 呈报人修改页面 联系人列表
	 */
	@RequestMapping(value = "/initListFlow.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initListFlow(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String mfrId = request.getParameter("mfrId");
		String modId = request.getParameter("modId");

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		MfrRlPsnQC qc = new MfrRlPsnQC();
		qc.setMfrId(Long.valueOf(mfrId));
		qc.setIsDel(BaseConstant.IS_YESNO_NO);
		page.setCondition(qc);

		Pager pager = this.mfrRlPsnService.searchListPage(page);
		List<MfrRlPsnVO> voList = (List<MfrRlPsnVO>) pager.getResultList();
		List<MfrRlPsnDTO> resultList = MfrRlPsnVOTransform.toDTOList(voList);

		if(StringUtils.isNotEmpty(modId)){
			MfrInfoModDtlQC mfrInfoModDtlQC = new MfrInfoModDtlQC();
			mfrInfoModDtlQC.setModId(Long.valueOf(modId));
			mfrInfoModDtlQC.setIsDel(BaseConstant.IS_YESNO_NO);
			mfrInfoModDtlQC.setTabNm(MfrInfoConstant.MFR_RL_PSN_FLOW_S_H_MFR_TAB);
			List<MfrInfoModDtlDTO> mfrInfoModDtlDTOS = this.mfrInfoModDtlApiService.searchMfrInfoModDtlDTOList(mfrInfoModDtlQC);
			Map<Long,List<MfrInfoModDtlDTO>> map = new HashMap<>();
			List<Long> ids = new ArrayList<>();
			if(CollectionUtils.isNotEmpty(mfrInfoModDtlDTOS)){
				for (MfrInfoModDtlDTO mfrInfoModDtlDTO: mfrInfoModDtlDTOS) {
					if(CommonOpTypCdEnum.MDF.getOpTypCd().equals(mfrInfoModDtlDTO.getModTypCd())){
						if(map.containsKey(mfrInfoModDtlDTO.getModBusId())){
							map.get(mfrInfoModDtlDTO.getModBusId()).add(mfrInfoModDtlDTO);
						}else{
							List<MfrInfoModDtlDTO> modDtlDTOS = new ArrayList<>();
							modDtlDTOS.add(mfrInfoModDtlDTO);
							map.put(mfrInfoModDtlDTO.getModBusId(),modDtlDTOS);
						}
					}else if(CommonOpTypCdEnum.DEL.getOpTypCd().equals(mfrInfoModDtlDTO.getModTypCd())){
						ids.add(mfrInfoModDtlDTO.getModBusId());
					}
				}
			}
			for (MfrRlPsnDTO mfrRlPsnDTO: resultList) {
				List<MfrInfoModDtlDTO> dtlDTOS = map.get(mfrRlPsnDTO.getId());
				if(CollectionUtils.isNotEmpty(dtlDTOS)){
					for (MfrInfoModDtlDTO modDtlDTO:dtlDTOS) {
						Field field = null;
						try {
							field = BaseMfrRlPsnDTO.class.getDeclaredField(modDtlDTO.getModAttrFiled());
						} catch (NoSuchFieldException e) {
							e.printStackTrace();
						}
						field.setAccessible(true);
						try {
							field.set((Object) mfrRlPsnDTO, modDtlDTO.getModConAft());
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
					}
				}
			}
			if(CollectionUtils.isNotEmpty(ids)){
				List<MfrRlPsnDTO> list1 = new ArrayList<MfrRlPsnDTO>();
				for (MfrRlPsnDTO dto : resultList ) {
					if(!ids.contains(dto.getId())){
						list1.add(dto);
					}
				}
				resultList = list1;
			}

		}
		//将未存在的必输联系人添加
		List<MfrRlPsnVO> list = MfrRlPsnVOTransform.toVOList(resultList);
		ListPageVO<MfrRlPsnVO> listPage = new ListPageVO<MfrRlPsnVO>(list, pager.getTotalCount());
		BaseLogUtils.newWebLogger("初始化供应商联系人列表页面数据").setLogOperType(LogOperEnum.RESP)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
				.setWarning(false)
				.setKeys("listPage", JSON.toJSONString(listPage))
				.info();
		return listPage;
	}

	/**
	 * 删除厂商联系人数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeMfrRlPsnByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.newWebLogger("删除厂商联系人数据,主键参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			return result;
		}

		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}

		try {
			boolean success = this.mfrRlPsnService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.newWebLogger("删除厂商联系人数据失败").setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
						.setWarning(false)
						.warn(LogExceptionEnum.COMMON_CODE_0002);
			}
			BaseLogUtils.newWebLogger("删除厂商联系人数据").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.setKeys("ID", JSON.toJSONString(idsList))
					.info();
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("删除厂商联系人数据失败，业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("删除厂商联系人数据失败，系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}

		return result;
	}

}

